<template>
  <div class="related-tasks-tab">
    <div class="tab-header">
      <div class="header-info">
        <span class="task-count">关联任务（{{ relatedTasks.length }}）</span>
      </div>
      <el-button 
        type="primary" 
        size="small" 
        @click="handleAddTask"
        :disabled="!requirementId"
      >
        <el-icon><Plus /></el-icon>
        添加任务
      </el-button>
    </div>

    <div v-loading="loading" class="tasks-list">
      <el-table
        v-if="relatedTasks.length > 0"
        :data="relatedTasks"
        size="default"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="title" label="任务标题" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link 
              type="primary" 
              @click="handleViewTask(row.id)"
              :underline="false"
            >
              {{ row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.status)" 
              size="small"
            >
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="90">
          <template #default="{ row }">
            <el-tag 
              :type="getPriorityType(row.priority)" 
              size="small"
            >
              {{ getPriorityName(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assignee_name" label="负责人" width="100" show-overflow-tooltip />
        <el-table-column prop="due_date" label="截止日期" width="110">
          <template #default="{ row }">
            {{ formatDate(row.due_date) || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleEditTask(row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleRemoveTask(row)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="暂无关联任务" :image-size="80" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getTaskList } from '@/api/task'
import type { Task } from '@/api/task'
import { formatDate } from '@/utils/date'
import { useTaskStates } from '@/composables/useTaskStates'
import { versionAPI, RelationType } from '@/api/version'

interface Props {
  requirementId: string
  currentTaskId?: string
  versionIds?: string[]
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'task-updated'): void
  (e: 'create-task'): void
}>()

const { loadStates, getStateName, getStateColor } = useTaskStates()
const loading = ref(false)
const relatedTasks = ref<Task[]>([])

// 加载关联任务列表
const loadRelatedTasks = async () => {
  if (!props.requirementId) {
    relatedTasks.value = []
    return
  }

  try {
    loading.value = true
    await loadStates()
    
    const response = await getTaskList({
      requirement_id: props.requirementId,
      size: 100
    })
    
    relatedTasks.value = response.items || []
  } catch (error) {
    console.error('加载关联任务失败:', error)
    ElMessage.error('加载关联任务失败')
    relatedTasks.value = []
  } finally {
    loading.value = false
  }
}

// 添加任务
const handleAddTask = () => {
  // 触发事件，让父组件打开创建任务对话框
  emit('create-task')
}

// 查看任务
const handleViewTask = (taskId: string) => {
  // 触发事件，让父组件打开任务详情
  window.open(`/tasks/${taskId}`, '_blank')
}

// 编辑任务
const handleEditTask = (task: Task) => {
  // 触发事件，让父组件打开任务编辑对话框
  window.open(`/tasks/${task.id}`, '_blank')
}

// 移除任务关联
const handleRemoveTask = async (task: Task) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除任务"${task.title}"的关联吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 如果有版本ID，需要从版本中移除任务关联
    if (props.versionIds && props.versionIds.length > 0) {
      const removePromises = props.versionIds.map(versionId =>
        versionAPI.removeTaskFromVersion(versionId, task.id).catch(error => {
          console.error(`从版本 ${versionId} 移除任务失败:`, error)
          return null
        })
      )
      await Promise.all(removePromises)
    }

    ElMessage.success('任务关联已移除')
    await loadRelatedTasks()
    emit('task-updated')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除任务关联失败:', error)
      ElMessage.error('移除任务关联失败')
    }
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, 'success' | 'info' | 'warning' | 'danger'> = {
    done: 'success',
    todo: 'info',
    in_progress: 'warning',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态名称
const getStatusName = (status: string) => {
  return getStateName(status) || status
}

// 获取优先级类型
const getPriorityType = (priority: string) => {
  const priorityMap: Record<string, 'success' | 'info' | 'warning' | 'danger'> = {
    low: 'info',
    medium: 'success',
    high: 'warning',
    urgent: 'danger'
  }
  return priorityMap[priority] || 'info'
}

// 获取优先级名称
const getPriorityName = (priority: string) => {
  const priorityMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急'
  }
  return priorityMap[priority] || priority
}

// 监听需求ID变化
watch(() => props.requirementId, (newId) => {
  if (newId) {
    loadRelatedTasks()
  } else {
    relatedTasks.value = []
  }
}, { immediate: true })

// 监听当前任务ID变化，如果新创建了任务，刷新列表
watch(() => props.currentTaskId, () => {
  if (props.currentTaskId && props.requirementId) {
    loadRelatedTasks()
  }
})

onMounted(() => {
  if (props.requirementId) {
    loadRelatedTasks()
  }
})
</script>

<style scoped lang="scss">
.related-tasks-tab {
  .tab-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;

    .header-info {
      .task-count {
        font-size: 14px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .tasks-list {
    min-height: 200px;
  }
}
</style>

